package com.oracle.lingshangejia.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lws.basic.utils.common.AdapterIntegerDefault0;
import com.lws.basic.utils.common.DoubleDefault0Adapter;
import com.lws.basic.utils.common.GsonUtils;
import com.oracle.children.ChildrenArchivesActivity;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.activity.HealthCheckArchivesActivity;
import com.oracle.lingshangejia.activity.LoginActivity;
import com.oracle.lingshangejia.activity.special.ChanHou42MainActivity;
import com.oracle.lingshangejia.activity.special.ChanHouActivity;
import com.oracle.lingshangejia.activity.special.ChanJian25Activity;
import com.oracle.lingshangejia.activity.special.ChanjianArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTong12ArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTong18ArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTong36ArchivesActivity;
import com.oracle.lingshangejia.activity.special.ErTongZhongYiActivity;
import com.oracle.lingshangejia.activity.special.HighBloodPpressureActivity;
import com.oracle.lingshangejia.activity.special.LaoNianRenActivity;
import com.oracle.lingshangejia.activity.special.TangNiaoBingActivity;
import com.oracle.lingshangejia.adapter.VisitRecodeAdapter;
import com.oracle.lingshangejia.bean.DataBean;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.bean.VisitRecordBean;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.mvp.base.BaseFragment;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.RxUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
//问询改随访

public class MarkFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.rv)
    RecyclerView mRv;
    Unbinder unbinder;
    private VisitRecodeAdapter mAdapter;
    private int mOffset =0;
    private int mLimit =10;


    @Override
    public int setLayoutId() {
        return R.layout.fragment_mark1;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        unbinder = ButterKnife.bind(this, view);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        super.initData();
        initRecyclerView();
        initRefresh();
        getData();
    }

    private void initRecyclerView() {
        mRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new VisitRecodeAdapter(null);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mRv.setAdapter(mAdapter);
    }

    private void initRefresh() {
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadmore();
               // mSrl.finishLoadmore();
            }
        });
    }

    private void loadmore(){
        showLoading();
        mOffset +=10;
        Observable.create(new ObservableOnSubscribe<VisitRecordBean>() {
            @Override
            public void subscribe(ObservableEmitter<VisitRecordBean> emitter) throws Exception {
                Map<Object, Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark", 1);
                map.put("offset", mOffset);
                map.put("limit", mLimit);
                map.put("createBy", User.getUserId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkgoNetwork.post(Constant.all_visit_record, jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, VisitRecordBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<VisitRecordBean>() {
            @Override
            public void onNext(VisitRecordBean bean) {
                if (bean.getMsg().equals("Token已过期")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));

                } else {
                    if (bean.getData() != null && bean.getData().getRows().size() > 0) {
                        mAdapter.addData(bean.getData().getRows());
                    } else {
                        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
                        mAdapter.setEmptyView(emptyView);
                        MyToast.show("没有随访记录");
                    }
                }
                mSrl.finishLoadmore();
                dismissLoading();
            }
        });
    }

    //获取当前医生随访记录
    private void getData() {
        mOffset=0;
        mLimit = 10;
        showLoading();
        Observable.create(new ObservableOnSubscribe<VisitRecordBean>() {
            @Override
            public void subscribe(ObservableEmitter<VisitRecordBean> emitter) throws Exception {
                Map<Object, Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark", 1);
                map.put("offset", mOffset);
                map.put("limit", mLimit);
                map.put("createBy", User.getUserId());
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkgoNetwork.post(Constant.all_visit_record, jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, VisitRecordBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<VisitRecordBean>() {
            @Override
            public void onNext(VisitRecordBean bean) {
                if (bean.getMsg().equals("Token已过期")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));

                } else {
                    if (bean.getData() != null && bean.getData().getRows().size() > 0) {
                        mAdapter.setNewData(bean.getData().getRows());
                    } else {
                        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
                        mAdapter.setEmptyView(emptyView);
                        MyToast.show("没有随访记录");
                    }
                }
                mSrl.finishRefresh();
                dismissLoading();
            }
        });


    }


    @OnClick({R.id.iv_app_push, R.id.iv_postpone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_app_push://推送
                new MaterialDialog.Builder(getContext())
                        .title("app通知下发")
                        .content("是否给居民发消息")
                        .positiveText("确认")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                 Observable.create(new ObservableOnSubscribe<DataBean>() {
                                     @Override
                                     public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                                         showLoading();
                                         List<Integer> list =new ArrayList<>();
                                         for (VisitRecordBean.DataBean.RowsBean rowsBean:mAdapter.getData()){

                                             if (rowsBean.isIs()){
                                                list.add(rowsBean.getId());
                                             }
                                         }
                                         Map<Object, Object> map = new HashMap<>();
                                         map.put("token", User.getToken());
                                         map.put("mark", 1);
                                         map.put("sfjlids",list);
                                         JSONObject jsonObject = new JSONObject(map);
                                         MyLogger.i(jsonObject.toString());
                                         String json = OkgoNetwork.post(Constant.app_push, jsonObject.toString());
                                         Gson gson = new Gson();
                                         MyLogger.i(json);
                                         emitter.onNext(gson.fromJson(json, DataBean.class));


                                     }
                                 }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
                                     @Override
                                     public void onNext(DataBean dataBean) {
                                                dismissLoading();
                                                if (dataBean.getCode()==0){
                                                    MyToast.show("发送成功");
                                                    getData();
                                                }else {
                                                    MyToast.show(dataBean.getMsg());
                                                }


                                                dialog.dismiss();
                                     }
                                 });
                            }
                        })
                        .onNeutral(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                break;
            case R.id.iv_postpone://延期

                new MaterialDialog.Builder(getContext())
                        .title("延期")
                        .content("")
                        .inputType(InputType.TYPE_CLASS_NUMBER)
                        .input("请输入天数", null, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                if (!TextUtils.isEmpty(input)) {
                                    Observable.create(new ObservableOnSubscribe<DataBean>() {
                                        @Override
                                        public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                                            showLoading();
                                            List<Integer> list = new ArrayList<>();
                                            for (VisitRecordBean.DataBean.RowsBean rowsBean : mAdapter.getData()) {
                                                if (rowsBean.isIs()) {
                                                    list.add(rowsBean.getId());
                                                }
                                            }
                                            Map<Object, Object> map = new HashMap<>();
                                            map.put("token", User.getToken());
                                            map.put("mark", 1);
                                            map.put("sfjlids", list);
                                            map.put("days", Integer.valueOf(input.toString()));
                                            JSONObject jsonObject = new JSONObject(map);
                                            MyLogger.i(jsonObject.toString());
                                            String json = OkgoNetwork.post(Constant.postpone, jsonObject.toString());
                                            Gson gson = GsonUtils.getInstance();
                                            emitter.onNext(gson.fromJson(json, DataBean.class));


                                        }

                                    }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
                                        @Override
                                        public void onNext(DataBean dataBean) {
                                            dismissLoading();
                                            if (dataBean.getCode() == 0) {
                                                getData();
                                                MyToast.show("延期成功");
                                            } else {
                                                MyToast.show(dataBean.getMsg());
                                            }


                                            dialog.dismiss();
                                        }
                                    });
                                }else {
                                    MyToast.show("天数不能为空");
                                }
                            }
                        })
                        .positiveText("确定")
                        .show();


                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List<VisitRecordBean.DataBean.RowsBean> list = (List<VisitRecordBean.DataBean.RowsBean>)mAdapter.getData();
        Intent intent = new Intent();
        intent.putExtra("jmid", list.get(position).getGrjbxxId());
        intent.putExtra("id", list.get(position).getId());
        if (list.get(position).getSfResult()==7){
            MyToast.show("该随访任务已经完成");
        }else {
            switch (list.get(position).getZxName()) {
                case "新生儿家庭访视记录":
                    intent.setClass(getActivity(), ChildrenArchivesActivity.class);
                    break;
                case "高血压患者随访记录":
                    intent.setClass(getActivity(), HighBloodPpressureActivity.class);
                    break;
                case "2型糖尿病患者健康随访记录":
                    intent.setClass(getActivity(), TangNiaoBingActivity.class);
                    break;
                case "老年人中医药健康管理":
                    intent.setClass(getActivity(), LaoNianRenActivity.class);
                    break;
                case "1到8月龄儿童健康检查记录":
                    intent.setClass(getActivity(), ErTong18ArchivesActivity.class);
                    break;
                case "12到30月龄儿童健康检查记录":
                    intent.setClass(getActivity(), ErTong12ArchivesActivity.class);
                    break;
                case "3到6岁儿童健康检查记录":
                    intent.setClass(getActivity(), ErTong36ArchivesActivity.class);
                    break;
                case "儿童中医药健康管理服务记录":
                    intent.setClass(getActivity(), ErTongZhongYiActivity.class);
                    break;
                case "孕产妇一次产前检查记录":
                    intent.setClass(getActivity(), ChanjianArchivesActivity.class);
                    break;
                case "孕产妇2到5次产前随访服务记录":
                    intent.setClass(getActivity(), ChanJian25Activity.class);
                    break;
                case "孕产妇产后访视记录":
                    intent.setClass(getActivity(), ChanHouActivity.class);
                    break;
                case "孕产妇产后42天健康检查记录":
                    intent.setClass(getActivity(), ChanHou42MainActivity.class);
                    break;
                case "健康体检表":
                    intent.setClass(getActivity(), HealthCheckArchivesActivity.class);
                    break;

            }
            startActivity(intent);
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        if (((CheckBox)view).isChecked()){
            mAdapter.getData().get(position).setIs(true);
        }else {
            mAdapter.getData().get(position).setIs(false);
        }
    }
}
